﻿using K8.CBB;
using K8.EF;
using KingerRobot.PCRBW.Dao;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;

namespace KingerRobot.PCRBW.SpiService;

public class MesOutOrdersRepositories : IMesOutOrdersRepositories
{
    #region 同步方法
    public MesOutOrder QueryById(string objId)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.FirstOrDefault(d => d.Id == objId);
    }

    /// <summary>
    /// 功能描述:根据ID查询数据
    /// 作　　者:Robin
    /// </summary>
    /// <param name="lstIds">id列表,如果是联合主键，请使用Where条件</param>
    /// <returns>数据实体列表</returns>
    public List<MesOutOrder> QueryByIDs(object[] lstIds)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Where(d => lstIds.Contains(lstIds)).ToList();
    }

    /// <summary>
    /// 写入实体数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns>插入个数 插入成功为1</returns>
    public int Add(MesOutOrder entity)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Insert(entity);
    }

    /// <summary>
    /// 批量插入实体
    /// </summary>
    /// <param name="listEntity">实体集合</param>
    /// <returns>影响行数</returns>
    public int Add(IEnumerable<MesOutOrder> listEntity)
    {
        var _db = Db.Default;
        _db.MesOutOrders.AddRange(listEntity);
        int insertedCount = _db.SaveChanges();
        return insertedCount;
    }
    /// <summary>
    /// 根据实体删除一条数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns></returns>
    public int DeleteById(string id)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Where(d => d.Id == id).Delete();
    }

    /// <summary>
    /// 删除指定ID集合的数据(批量删除)
    /// </summary>
    /// <param name="ids">主键ID集合</param>
    /// <returns></returns>
    public int Deletes(IEnumerable<MesOutOrder> entitys)
    {
        try
        {
            var _db = Db.Default;
            _db.MesOutOrders.BulkDelete(entitys);
            int result = _db.SaveChanges();
            return result;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }
    /// <summary>
    /// 更新实体数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns></returns>
    public int Update(MesOutOrder entity)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Update<MesOutOrder>(entity);
    }
    /// <summary>
    /// 待条件更新所有数据
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <param name="entity"></param>
    /// <returns></returns>
    public int Update(Expression<Func<MesOutOrder, bool>> whereExpression, MesOutOrder entity)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Where(whereExpression).Update(entity);
    }

    /// <summary>
    /// 正序查询第一条数据
    /// </summary>
    /// <returns></returns>
    public MesOutOrder First()
    {
        var _db = Db.Default;
        return _db.MesOutOrders.First();
    }
    /// <summary>
    /// 查询第一条数据
    /// </summary>
    /// <param name="whereExpression"></param>
    /// <returns></returns>
    public MesOutOrder First(Expression<Func<MesOutOrder, bool>> whereExpression)
    {
        var _db = Db.Default;
        if (whereExpression == null) return null;
        return _db.MesOutOrders.Where(whereExpression).OrderBy(d=>d.CreateTime).FirstOrDefault(whereExpression);
    }


    /// <summary>
    /// 功能描述:查询所有数据
    /// 作　　者:Robin
    /// </summary>
    /// <returns>数据列表</returns>
    public List<MesOutOrder> Query()
    {
        try
        {
            var _db = Db.Default;
            return _db.MesOutOrders.ToList();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Query执行异常:{ex.Message}");
        }
        return null;
    }


    /// <summary>
    /// 功能描述:查询数据列表
    /// 作　　者:Robin
    /// </summary>
    /// <param name="whereExpression">whereExpression</param>
    /// <returns>数据列表</returns>
    public List<MesOutOrder> Query(Expression<Func<MesOutOrder, bool>> whereExpression)
    {
        var _db = Db.Default;
        if (whereExpression == null) return null;
        return _db.MesOutOrders.Where(whereExpression).ToList();
    }


    /// <summary>
    /// 根据sql语句查询
    /// </summary>
    /// <param name="strSql">完整的sql语句</param>
    /// <param name="parameters">参数</param>
    /// <returns>泛型集合</returns>
    public List<MesOutOrder> QuerySql(string strSql, Parameter[] parameters = null)
    {
        var _db = Db.Default;
        var result = _db.MesOutOrders.FromSqlRaw(strSql, parameters).ToList();

        return result;
    }
    /// <summary>
    /// 根据sql语句查询 执行update、delete、add
    /// </summary>
    /// <param name="strSql">完整的sql语句</param>
    /// <returns>泛型集合</returns>
    public int ExecuteSqlRaw(string strSql, Parameter[] parameters)
    {
        var dbHelper = new DbHelper();
        dbHelper.CommandText = strSql.ToString();
        dbHelper.CommandType = System.Data.CommandType.Text;
        for (int i = 0; i < parameters.Length; i++)
        {
            dbHelper.AddParameter(parameters[i]);
        }
        int rowsReturned = dbHelper.ExecuteNonQuery();

        return rowsReturned;
    }

    #endregion


    public MesOutOrder GetMesOutOrderCompleteByStatus(string targetName, int status)
    {
        MesOutOrder result = null;//出库

        var db = Db.Default;
        var sdLoc = db.RcsLocations.FirstOrDefault(d=>d.LocCode== targetName);
        #region
        var list = (from o in db.MesOutOrders
                  join
                  r0 in db.RcsEquips on o.TargetEquip equals r0.EquipCode
                  join
                  l in db.WcsEquipLocHolds on r0.Id equals l.LocId
                  join
                  h in db.WcsEquipLocHolds on l.EquipId equals h.LocId
                  where h.AreaId == 888 && o.StopFlag == "N"  &&  o.Status == status && h.LocId== sdLoc.Id
                    select o).ToList();
        if (list is null || list.Count<=0)
        {
            WriteLog($"桁架任务查询》未查询到任务，任务状态:[{status}]", true);
            return null;
        }
        #endregion
        result = list.OrderBy(d => d.CreateTime).FirstOrDefault();
        return result;
    }

    /// <summary>
    /// 执行出库更新状态事务
    /// </summary>
    /// <returns></returns>
    public int ExecUpdateExWarehousStatusTran(MesOutOrder mesOutOrder, PORcsLocation rcsLocation, POWcsTask task)
    {
        var _db = Db.Default;
        int result = 0;
        try
        {
            var mesProduct = _db.MesProducts.FirstOrDefault(d => d.Id == rcsLocation.Pid);
            if (mesProduct==null)
            {
                return -13;
            }
            //添加事务
            using (var transaction = _db.Database.BeginTransaction())
            {
                result = _db.MesOutOrders.Where(d => d.Id == mesOutOrder.Id).Update(new MesOutOrder()
                {
                    Status = mesOutOrder.Status,
                });
                result = _db.RcsLocations.Where(d => d.Id == rcsLocation.Id).Update(new PORcsLocation()
                {
                    TaskId = rcsLocation.TaskId,
                    TaskOccupy = rcsLocation.TaskOccupy,
                    TaskOccupyTime = rcsLocation.TaskOccupyTime,
                    LocHasSku = rcsLocation.LocHasSku,
                    SkuRealCount = rcsLocation.SkuRealCount,
                    UpdateTime = rcsLocation.UpdateTime,
                    LocHasSkuTime = rcsLocation.LocHasSkuTime,
                    MaterialId = rcsLocation.MaterialId,
                    ProductBatch = rcsLocation.ProductBatch,
                    MdTime = rcsLocation.MdTime,
                    Remarks = rcsLocation.Remarks,
                    Pid = null,
                    LocSize = rcsLocation.LocSize
                });
                if (task.Mark == 2)
                {
                    _db.MesOutCompletes.Add(new MesOutComplete()
                    {
                        Id = XID.Nextval.ToString(),
                        ListNo = mesOutOrder.Id,
                        PartNumber = mesProduct.PartNumber,
                        BatchName = mesProduct.BatchName,
                        ElocNo = string.Empty,
                        RfidNo = "",
                        CreateTime = DateTime.Now,
                        CreateUser = "WMS",
                        last_modfied_time = DateTime.Now,
                        last_modfied_user = "WMS",
                        remarks = string.Empty,
                        update_flag = 1,
                        area_name = "物料出库",
                        storage_no = "ST_01",
                        target_equip = mesOutOrder.TargetEquip,
                        out_flag = 1,
                        print_time = null,
                        out_time = DateTime.Now,
                        part_desc = mesProduct.MaterialDesc,
                        list_status = "0",
                        data_type = "Lot-1",
                        quantity = mesProduct.Quantity,
                        complete_type = "0",
                        InSize = int.Parse(mesProduct.innerdiameter.ToString())
                    });
                }
                _db.MesProducts.Where(d => d.Id == mesProduct.Id).Update(new MesProduct()
                {
                    Status = 3,
                });
              _db.SaveChanges();
                transaction.Commit();
            }
            return result;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"执行入库任务更新表" });
        }
        return result;

    }

    /// <summary>
    /// 执行桁架任务更新状态事务
    /// </summary>
    /// <returns></returns>
    public int ExecUpdateTrussStatusTran(MesOutOrder mesOutOrder, MesProduct mesProduct, PORcsLocation rcsLocation)
    {
        var _db = Db.Default;
        int result = 0;
        try
        {
            //添加事务
            using (var transaction = _db.Database.BeginTransaction())
            {
                result = _db.MesOutOrders.Where(d => d.Id == mesOutOrder.Id).Update(mesOutOrder);
                result = _db.MesProducts.Where(d => d.Id == mesProduct.Id).Update(mesProduct);
                result = _db.RcsLocations.Where(d => d.Id == rcsLocation.Id).Update(rcsLocation);
                _db.MesOutCompletes.Add(new MesOutComplete()
                {
                    Id = XID.Nextval.ToString(),
                    ListNo = mesOutOrder.Id,
                    PartNumber = mesProduct.PartNumber,
                    BatchName = mesProduct.BatchName,
                    ElocNo = string.Empty,
                    RfidNo = "",
                    CreateTime = DateTime.Now,
                    CreateUser = "WMS",
                    last_modfied_time = DateTime.Now,
                    last_modfied_user = "WMS",
                    remarks = string.Empty,
                    update_flag = 1,
                    area_name = "物料出库",
                    storage_no = "ST_01",
                    target_equip = mesOutOrder.TargetEquip,
                    out_flag = 1,
                    print_time = null,
                    out_time = DateTime.Now,
                    part_desc = mesProduct.MaterialDesc,
                    list_status = "0",
                    data_type = "Lot-1",
                    quantity = mesProduct.Quantity,
                    complete_type = "0",
                    InSize = int.Parse(mesProduct.innerdiameter.ToString())
                });
                _db.SaveChanges();
                transaction.Commit();
                result = 2;
            }
            return result;
        }
        catch (Exception ex)
        {
            K8.LSF.Client.Log(new K8.LSF.Log { Data = $"执行入库任务更新表" });
        }
        return result;

    }


    /// <summary>
    /// 指定更新实体数据
    /// </summary>
    /// <param name="entity">博文实体类</param>
    /// <returns></returns>
    public int UpdateByOrder(MesOutOrder entity)
    {
        var _db = Db.Default;
        return _db.MesOutOrders.Where(d=>d.Id==entity.Id).Update<MesOutOrder>(new MesOutOrder {
            Id = entity.Id,
            PartNumber = entity.PartNumber,
            Grade = entity.Grade,
            RequireCount = entity.RequireCount,
            ActionCount = entity.RequireCount,
            ShipCount = entity.ShipCount,
            StopFlag = entity.StopFlag,
            ErrorFlag = entity.ErrorFlag,
            Remarks = entity.Remarks,
            BatchName = entity.BatchName,
            PartClass = entity.PartClass,
            TargetEquip = entity.TargetEquip,
            UpdateTime = entity.UpdateTime,
            UpdateUser = entity.UpdateUser,
            UpdateFlag = entity.UpdateFlag,
            ErrorInfo = entity.ErrorInfo,
            MPartNumber = entity.MPartNumber,
            MPartRevision = entity.MPartRevision,
            TraceCode = entity.TraceCode,
            AreaName = entity.AreaName,
            Innerdiameter = entity.Innerdiameter,
        });
    }
}
